<template>
  <van-nav-bar id="titlebar" :fixed="true" title=""
               left-text="返回"
               left-arrow
               @click-left="onClickLeft"
               @click-right="onClickRight"
               :placeholder="true">、
    <template #right>
      <van-icon  name="passed" size="24" />
    </template>
  </van-nav-bar>
  <div class="main_input">
    <div style="text-align: left;margin-top: 20px">
      <div class="wb_icon"  >
        <img src="../assets/photo.png" alt="" @click="iputopen(1)">
        <input type="file" id = "imgInput"  ref="photoIn" name = "file" multiple="multiple" accept="image/*"   style="display: none;" @change="selectFile(1)" />
      </div>
      <div class="wb_icon"  >
        <img src="../assets/video.png" alt="" @click="iputopen(2)">
        <input type="file" id = "videoInput" ref="videoIn" name = "file"  multiple="multiple" accept="video/*"   style="display: none;" @change="selectFile(2)" />
      </div>
    </div>
    <van-field
        v-model="content.text"
        rows="5"
        autosize
        type="textarea"
        maxlength="100"
        placeholder="分享新鲜事..."
        show-word-limit
    />
    <div  class="showImg">
      <div v-for="(item, index) in content.showVideoList"   style="display: inline-block;margin-left: 10px;margin-right: 10px;position: relative">
        <video style="width: 100px; height: 100px" playsinline  muted = "true"  autoplay loop :src= "item" @click = "showPreV(index)" ></video>
        <img src="../assets/xx.png" class="deleteImg" @click="deletePhoto(2,index)">
      </div>
    </div>

    <van-image-preview
        v-model:show="content.videoPreview"
        :images="content.showVideoList"
        :close-on-click-image="false"
        :start-position = content.videoIndex
        :closeable = "true"
        :before-close="stopVideo"
    >
      <template #image="{ src }">
        <video ref="videoPre" style="width: 85%;" autoplay loop playsinline  controls muted = "true">
          <source :src="src" />
        </video>
      </template>
    </van-image-preview>
      <van-divider v-if="content.videoFileList.length > 0" :style="{ padding: '0 16px' }" />
      <div  class="showImg">
      <div v-for="(item, index) in content.showImgList"   style="display: inline-block;margin-left: 10px;margin-right: 10px;position: relative">
        <van-image style="width: 100px; height: 100px"  :src="item"  fit="cover"  @click = "showPre(index)" />
        <img src="../assets/xx.png" class="deleteImg" @click="deletePhoto(1,index)">
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, unref,onUnmounted} from "vue";
import {useRouter,useRoute} from 'vue-router'
import {send_wb, send_wb_file} from '@/axios/weibo'
import {closeToast, showFailToast, showImagePreview, showLoadingToast} from 'vant';
import {uploadStore} from "@/stores/UploadStorage.js";

const router = useRouter();

const onClickLeft = () => history.back();
//输入框
const photoIn = ref(null);
//输入框
const videoIn = ref(null);
//video标签
const videoPre = ref(null);
const upLoad = uploadStore()

const content = reactive({
  imgLimit: 9,
  videoLimit: 3,
  text :"",
  imgFileList: [],
  videoFileList: [],
  showImgList: [],
  showVideoList: [],
  loading : false,
  videoPreview: false,
  videoIndex: 0
})
const MAX_SIZE = 68 * 1024 * 1024;


const stopVideo = () => {
    if (videoPre.value) {
        videoPre.value.pause(); // 暂停视频
    }
    return true;
}

const iputopen = (n) => {

    let input = document.querySelector("#imgInput")
    if(n == 2){
      input = document.querySelector("#videoInput")
    }

    input.click();
}

const selectFile = (n) =>{

  let  files = []
  if (n == 1){
    files.push(...unref(photoIn).files)
    if(files.length + content.imgFileList.length > content.imgLimit){
      showFailToast("当前只支持选择"+ content.imgLimit +"个图片")
      return
    }
  }
  if (n == 2){
    files.push(...unref(videoIn).files)
    if(files.length + content.videoFileList.length > content.videoLimit){
      showFailToast("当前只支持选择"+ content.videoLimit +"个视频")
      return
    }
  }


  if(n == 1){

    Array.from(unref(photoIn).files).forEach((item) => {
      // let ff = {
      //   type: "",
      //   value: ""
      // }

      content.imgFileList.push(item)
      content.showImgList.push( URL.createObjectURL(item))
    })
    unref(photoIn).value = null

  }
  if (n == 2){
    Array.from(unref(videoIn).files).forEach((item, index) => {
      // let ff = {
      //   type: "",
      //   value: ""
      // }
      console.log(item.size)
      if (item.size > MAX_SIZE){
        showFailToast("第"+ (index + 1) +"个视频太大了")
        return
      }

      content.videoFileList.push(item)
      content.showVideoList.push( URL.createObjectURL(item))
    })
    unref(videoIn).value = null

  }

}


const deletePhoto = (c,n) =>{

  if(c === 1){
    content.imgFileList.splice(n, 1)
    content.showImgList.splice(n, 1)
    URL.revokeObjectURL(content.showImgList[n])
  }
  if(c === 2){
    content.videoFileList.splice(n, 1)
    content.showVideoList.splice(n, 1)
    URL.revokeObjectURL(content.showVideoList[n])
  }

}
const showPreV = (n) =>{
  content.videoIndex = n
  content.videoPreview = true
    if (videoPre.value) {
        videoPre.value.play(); // 暂停视频
    }
}

const showPre = (n) =>{
  showImagePreview({
    images: content.showImgList,
    startPosition: n,
    loop:false
  });
}

const onClickRight = ()=>{
  if(!content.text && content.imgFileList.length ==0 && content.videoFileList.length ==0){
    showFailToast("请填写内容")
    return
  }

  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  });
  let formData = new FormData()
  if(content.text){
    formData.append("content" , content.text)
  }else {
    formData.append("content" , "分享图片")
  }
  if (content.imgFileList.length ==0 && content.videoFileList.length ==0){
    formData.append("hasFile" , false)
  }else {
    formData.append("hasFile" , true)
  }
  upLoad.loadingShow = true
  upLoad.loadingLen = 0
  send_wb(formData).then(res =>{
    let wbId = res.data.data
    let files = [...content.videoFileList,...content.imgFileList]
    let comp = []

    files.forEach((e, inx)=>{
      let typpe = e.type.indexOf("image") >= 0 ? 1 : 2
      let formData2 = new FormData()
      formData2.append("id", wbId)
      formData2.append("file", e)
      formData2.append("type", typpe)
      formData2.append("order", inx)
      send_wb_file(formData2).then(res =>{
          comp.push(inx)
          upLoad.setLoadLen(comp.length, files.length)
      }).catch(err=>{

      })
    })
    closeToast();
    router.push("/")
  }).catch(err=>{
    closeToast();
  })
}
onUnmounted(()=>{
  content.showImgList.forEach((item, index) => {
    URL.revokeObjectURL(item)
  })
  content.showVideoList.forEach((item, index) => {
    URL.revokeObjectURL(item)
  })
})

onUnmounted(() => {
  content.showImgList.forEach((item, index) => {
    URL.revokeObjectURL(item)
  })
  content.showVideoList.forEach((item, index) => {
    URL.revokeObjectURL(item)
  })
})

</script>

<style scoped>
.main_input{
  padding: 2px 0;

}
.wb_icon{
  width: 28px;
  display: inline-block;
  margin-left: 12px;
}
.wb_icon img{
  width: 100%;
}

.showImg{
  margin-top: 20px;
  text-align: left;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.deleteImg{
  width: 20px;
  position: absolute;
  right: -4px;
  top: -4px;
}
</style>